package com.example.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionController {
    public static void main(String[] args) {
        Think think = new Think();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                think.s();
            }
      },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                think.s1();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                think.s3();
            }
        },"C").start();
    }
    }


class Think{
    Lock lock=new ReentrantLock();
    private Integer id=1;
    Condition condition = lock.newCondition();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    public void s(){
        lock.lock();
        try {
            while (id!=1){
                condition.await();
            }
            System.out.println("1");
            id=2;
            condition1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }
    public void s1(){
        lock.lock();
        try {
            while (id!=2){
                condition1.await();
            }
            System.out.println("2");
            id=3;
            condition2.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }

    public void s3(){
        lock.lock();
        try {
            while (id!=3){
                condition2.await();
            }
            System.out.println("3");
            id=1;
            condition.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }
}

